<template>
  <a-card :bordered="false">
    <!-- 查询区域 -->
    <div class="table-page-search-wrapper">
      <a-form layout="inline" @keyup.enter.native="searchQuery">
        <a-row :gutter="24">
          <a-col :xl="6" :lg="7" :md="8" :sm="24">
            <a-form-item label="状态">
              <a-select :default-value="''" v-model="queryParam.status" @change="searchQuery">
                <a-select-option :value="''">
                  全部
                </a-select-option>
                <a-select-option :value="1">
                  进行中
                </a-select-option>
                <a-select-option :value="2">
                  已完成
                </a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :xl="6" :lg="7" :md="8" :sm="24">
            <a-form-item label="操作时间">
              <j-date placeholder="请选择操作时间" v-model="queryParam.createTime"></j-date>
            </a-form-item>
          </a-col>
          <template v-if="toggleSearchStatus">
            <a-col :xl="6" :lg="7" :md="8" :sm="24">
              <a-form-item label="创建人">
                <a-input placeholder="请输入创建人" v-model="queryParam.createBy"></a-input>
              </a-form-item>
            </a-col>
          </template>
          <a-col :xl="6" :lg="7" :md="8" :sm="24">
            <span style="float: left;overflow: hidden;" class="table-page-search-submitButtons">
              <a-button type="primary" @click="searchQuery" icon="search">查询</a-button>
              <a-button type="primary" @click="searchReset" icon="reload" style="margin-left: 8px">重置</a-button>
              <a @click="handleToggleSearch" style="margin-left: 8px">
                {{ toggleSearchStatus ? '收起' : '展开' }}
                <a-icon :type="toggleSearchStatus ? 'up' : 'down'" />
              </a>
            </span>
          </a-col>
        </a-row>
      </a-form>
    </div>
    <!-- 查询区域-END -->

    <!-- 操作按钮区域 -->
    <div class="table-operator">
      <a-upload name="file" :showUploadList="false" :multiple="false" :headers="tokenHeader" :action="import1ExcelUrl" @change="handleImport1Excel">
        <a-button type="primary" icon="import">批量发货</a-button>
      </a-upload>
      <a-upload name="file" :showUploadList="false" :multiple="false" :headers="tokenHeader" :action="import2ExcelUrl" @change="handleImport2Excel">
        <a-button type="primary" icon="import">批量修改物流</a-button>
      </a-upload>
      <a-button type="primary" icon="download" @click="handleSendXls('批量(发货/修改物流)模板')">下载批量(发货/修改物流)模板</a-button>
      <a-button type="primary" icon="download" @click="handleWlXls('物流公司列表')">下载物流公司列表</a-button>

    </div>

    <!-- table区域-begin -->
    <div>

      <a-table ref="table" size="middle" bordered rowKey="id" :columns="columns" :dataSource="dataSource" :pagination="ipagination" :loading="loading"
        class="j-table-force-nowrap" @change="handleTableChange">

        <template slot="htmlSlot" slot-scope="text">
          <div v-html="text"></div>
        </template>
        <template slot="imgSlot" slot-scope="text">
          <span v-if="!text" style="font-size: 12px;font-style: italic;">无图片</span>
          <img v-else :src="getImgView(text)" height="55px" alt="" style="max-width:80px;font-size: 12px;font-style: italic;" />
        </template>
        <template slot="fileSlot" slot-scope="text">
          <span v-if="!text" style="font-size: 12px;font-style: italic;">无文件</span>
          <a-button v-else :ghost="true" type="primary" icon="download" size="small" @click="downloadFile(text)">
            下载
          </a-button>
        </template>

        <span slot="action" slot-scope="text, record">
          <a v-if="record.status==2" @click="handleViewXls(record)">{{record.code==1?'查看发货记录':'查看失败原因'}}</a>

        </span>

      </a-table>
    </div>

    <oms-order-delivery-task-modal ref="modalForm" @ok="modalFormOk"></oms-order-delivery-task-modal>
  </a-card>
</template>

<script>
import { deleteAction, getAction, downFile, getFileAccessHttpUrl } from '@/api/manage'
import '@/assets/less/TableExpand.less'
import { mixinDevice } from '@/utils/mixin'
import { JeecgListMixin } from '@/mixins/JeecgListMixin'
import OmsOrderDeliveryTaskModal from './modules/OmsOrderDeliveryTaskModal'
import JDate from '@/components/jeecg/JDate.vue'

export default {
  name: 'OmsOrderDeliveryTaskList',
  mixins: [JeecgListMixin, mixinDevice],
  components: {
    JDate,
    OmsOrderDeliveryTaskModal
  },
  data () {
    return {
      description: '批量发货管理页面',
      // 表头
      columns: [
        {
          title: '#',
          dataIndex: '',
          key: 'rowIndex',
          width: 60,
          align: "center",
          customRender: function (t, r, index) {
            return parseInt(index) + 1
          }
        },
        {
          title: '记录编号',
          align: "center",
          dataIndex: 'id'
        },
        {
          title: '操作时间',
          align: "center",
          dataIndex: 'createTime'
        },
        {
          title: '操作人',
          align: "center",
          dataIndex: 'createBy'
        },
        {
          title: '操作类型',
          align: "center",
          dataIndex: 'type',
          customRender: function (text) {
            return text == 1 ? "批量发货" : "批量修改物流"
          }
        },
        {
          title: '发货单数',
          align: "center",
          dataIndex: 'totalNum'
        },
        {
          title: '成功单数',
          align: "center",
          dataIndex: 'successNum'
        },
        {
          title: '状态',
          align: "center",
          dataIndex: 'status',
          customRender: function (text) {
            return text == 1 ? "进行中" : "已完成"
          }
        },
        {
          title: '操作',
          dataIndex: 'action',
          align: "center",
          fixed: "right",
          width: 147,
          scopedSlots: { customRender: 'action' }
        }
      ],
      url: {
        list: "/mallBase/omsOrderDeliveryTask/list",
        delete: "/mallBase/omsOrderDeliveryTask/delete",
        deleteBatch: "/mallBase/omsOrderDeliveryTask/deleteBatch",
        exportXlsUrl: "/mallBase/omsOrderDeliveryTask/exportSendXls",
        exportLogisticsXlsUrl: "/common/cmsLogisticsCompany/exportXls",
        exportResXlsUrl: "/mallBase/omsOrderDeliveryTask/exportResXls",
        importExcelUrl: "mallBase/omsOrderDeliveryTask/importExcel",
        import1ExcelUrl: "mallBase/omsOrderDeliveryTask/importSendExcel",
        import2ExcelUrl: "mallBase/omsOrderDeliveryTask/importLogisticsExcel"
      },
      dictOptions: {},
    }
  },
  created () {
  },
  computed: {
    importExcelUrl: function () {
      return `${window._CONFIG['domianURL']}/${this.url.importExcelUrl}`
    },
    import1ExcelUrl: function () {
      return `${window._CONFIG['domianURL']}/${this.url.import1ExcelUrl}`
    },
    import2ExcelUrl: function () {
      return `${window._CONFIG['domianURL']}/${this.url.import2ExcelUrl}`
    },
  },
  methods: {
    handleSendXls (fileName) {
      if (!fileName || typeof fileName != "string") {
        fileName = "导出文件"
      }
      let param = { ...this.queryParam }
      if (this.selectedRowKeys && this.selectedRowKeys.length > 0) {
        param['selections'] = this.selectedRowKeys.join(",")
      }
      console.log("导出参数", param)
      downFile(this.url.exportXlsUrl, param).then((data) => {
        if (!data) {
          this.$message.warning("文件下载失败")
          return
        }
        if (typeof window.navigator.msSaveBlob !== 'undefined') {
          window.navigator.msSaveBlob(new Blob([data], { type: 'application/vnd.ms-excel' }), fileName + '.xls')
        } else {
          let url = window.URL.createObjectURL(new Blob([data], { type: 'application/vnd.ms-excel' }))
          let link = document.createElement('a')
          link.style.display = 'none'
          link.href = url
          link.setAttribute('download', fileName + '.xls')
          document.body.appendChild(link)
          link.click()
          document.body.removeChild(link) //下载完成移除元素
          window.URL.revokeObjectURL(url) //释放掉blob对象
        }
      })
    },
    handleViewXls (record) {

      let fileName = record.code == 1 ? '查看发货记录' : '查看失败原因'
      downFile(this.url.exportResXlsUrl, { id: record.id }).then((data) => {
        if (!data) {
          this.$message.warning("文件下载失败")
          return
        }
        if (typeof window.navigator.msSaveBlob !== 'undefined') {
          window.navigator.msSaveBlob(new Blob([data], { type: 'application/vnd.ms-excel' }), fileName + '.xls')
        } else {
          let url = window.URL.createObjectURL(new Blob([data], { type: 'application/vnd.ms-excel' }))
          let link = document.createElement('a')
          link.style.display = 'none'
          link.href = url
          link.setAttribute('download', fileName + '.xls')
          document.body.appendChild(link)
          link.click()
          document.body.removeChild(link) //下载完成移除元素
          window.URL.revokeObjectURL(url) //释放掉blob对象
        }
      })
    },

    handleWlXls (fileName) {
      if (!fileName || typeof fileName != "string") {
        fileName = "导出文件"
      }
      let param = { ...this.queryParam }
      if (this.selectedRowKeys && this.selectedRowKeys.length > 0) {
        param['selections'] = this.selectedRowKeys.join(",")
      }
      console.log("导出参数", param)
      downFile(this.url.exportLogisticsXlsUrl, param).then((data) => {
        if (!data) {
          this.$message.warning("文件下载失败")
          return
        }
        if (typeof window.navigator.msSaveBlob !== 'undefined') {
          window.navigator.msSaveBlob(new Blob([data], { type: 'application/vnd.ms-excel' }), fileName + '.xls')
        } else {
          let url = window.URL.createObjectURL(new Blob([data], { type: 'application/vnd.ms-excel' }))
          let link = document.createElement('a')
          link.style.display = 'none'
          link.href = url
          link.setAttribute('download', fileName + '.xls')
          document.body.appendChild(link)
          link.click()
          document.body.removeChild(link) //下载完成移除元素
          window.URL.revokeObjectURL(url) //释放掉blob对象
        }
      })
    },
    /* 批量发货 */
    handleImport1Excel (info) {
      if (info.file.status !== 'uploading') {
        console.log(info.file, info.fileList)
      }
      if (info.file.status === 'done') {
        if (info.file.response.success) {
          // this.$message.success(`${info.file.name} 文件上传成功`);
          if (info.file.response.code === 201) {
            let { message, result: { msg, fileUrl, fileName } } = info.file.response
            let href = window._CONFIG['domianURL'] + fileUrl
            this.$warning({
              title: message,
              content: (
                <div>
                  <span>{msg}</span><br />
                  <span>具体详情请 <a href={href} target="_blank" download={fileName}>点击下载</a> </span>
                </div>
              )
            })
          } else {
            this.$message.success(info.file.response.message || `${info.file.name} 文件上传成功`)
          }
          this.loadData()
        } else {
          this.$message.error(`${info.file.name} ${info.file.response.message}.`)
        }
      } else if (info.file.status === 'error') {
        this.$message.error(`文件上传失败: ${info.file.msg} `)
      }
    },
    /* 批量修改物流 */
    handleImport2Excel (info) {
      if (info.file.status !== 'uploading') {
        console.log(info.file, info.fileList)
      }
      if (info.file.status === 'done') {
        if (info.file.response.success) {
          // this.$message.success(`${info.file.name} 文件上传成功`);
          if (info.file.response.code === 201) {
            let { message, result: { msg, fileUrl, fileName } } = info.file.response
            let href = window._CONFIG['domianURL'] + fileUrl
            this.$warning({
              title: message,
              content: (
                <div>
                  <span>{msg}</span><br />
                  <span>具体详情请 <a href={href} target="_blank" download={fileName}>点击下载</a> </span>
                </div>
              )
            })
          } else {
            this.$message.success(info.file.response.message || `${info.file.name} 文件上传成功`)
          }
          this.loadData()
        } else {
          this.$message.error(`${info.file.name} ${info.file.response.message}.`)
        }
      } else if (info.file.status === 'error') {
        this.$message.error(`文件上传失败: ${info.file.msg} `)
      }
    },
    initDictConfig () {
    }
  }
}
</script>
<style scoped>
@import '~@assets/less/common.less';
</style>